#include "tcpthread.h"
#include "mywidget.h"
Tcpthread::Tcpthread(int sockDesc,QObject *parent):
    QThread(parent),m_sockDesc(sockDesc)
{

}

Tcpthread::~Tcpthread()
{

}
void Tcpthread::run()
{

    m_socket=new QTcpSocket;
    QString clientIP;
    if(!m_socket->setSocketDescriptor(m_sockDesc))
    {
        qDebug()<<"Socket error";
        return;
    }
    clientIP=m_socket->peerAddress().toString();//得到所连接客户端的IP
    connect(m_socket,SIGNAL(readyRead()),this,SLOT(recvData()));
    //当客户端主动断开时，服务器这边也应该相应的断开
    connect(m_socket,SIGNAL(disconnected()),this,SLOT(disconnectToHost()));
    connect(this,SIGNAL(a()),this,SLOT(dis()));
    qDebug()<<"clientIP:"<<clientIP;
    emit connectTCP(clientIP,m_sockDesc);
    //由于在run函数中new一个QTcpSocket，所以需要启动事件exec，不然信号会发不出
    this->exec();

}
void Tcpthread::recvData()
{
    auto data=m_socket->readAll();
//    qDebug()<<"thread:"<<QString(data);
    emit dataReady(QString(data));
}

void Tcpthread::disconnectToHost()
{
    emit disconnectTCP(m_sockDesc);
    m_socket->disconnectFromHost();
//This function does nothing if the thread does not have an event loop.
//Tells the thread's event loop to exit with return code 0,对应着exec
    this->quit();
}
void Tcpthread::disconnectServer()
{
    qDebug()<<"断开了";
//    m_socket->disconnectFromHost();
//    this->quit();
 //   m_socket->close();
  disconnect(m_socket,SIGNAL(readyRead()),this,SLOT(recvData()));
}
void Tcpthread::sendDataSlot(const QByteArray &data)
{
    m_socket->write(data);
    qDebug()<<"发送成功";
}
